﻿#pragma once
#include "board.h"
#include "piece.h"
#include <vector>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <set>

// 是否继续游戏的标志
bool continuePlaying = true;

// 游戏模式枚举
enum class GameMode {
    TWO_PLAYER,
    PLAYER_VS_AI_STANDARD,
    PLAYER_VS_AI_ENHANCED,
    AI_VS_AI
};

// 位置结构体
struct Position {
    int row;
    int col;
};

// 评分相关数据结构
enum PatternType {
    FIVE = 0,       // 连五
    ALIVE_FOUR,     // 活四
    RUSH_FOUR,      // 冲四
    ALIVE_THREE,    // 活三
    SLEEP_THREE,    // 眠三
    ALIVE_TWO,      // 活二
    SLEEP_TWO,      // 眠二
    NONE            // 无价值
};

// 棋型对应分值（可根据需要调整）
const int patternScore[8] = {
    100000,  // 连五
    10000,   // 活四
    1000,    // 冲四
    500,     // 活三
    100,     // 眠三
    50,      // 活二
    10,      // 眠二
    0        // 无价值
};

// 中心权重矩阵（15x15）
const int centerWeight[BOARD_SIZE][BOARD_SIZE] = {
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
    {0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0},
    {0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 5, 6, 6, 6, 5, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 5, 6, 6, 6, 5, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0},
    {0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0},
    {0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0},
    {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};

// 游戏模式基类
class Game {
protected:
    Board board;
    std::vector<std::vector<Piece::Type>> boardState;
    Piece::Type currentPlayer;
    bool gameOver;
    // 添加历史记录相关成员
    struct MoveRecord {
        int row;
        int col;
        Piece::Type player;
    };
    std::vector<MoveRecord> moveHistory;

public:
    Game(Piece::Type _currentPlayer = Piece::PIECE_BLACK) : gameOver(false) {
		currentPlayer = _currentPlayer;
        boardState.resize(BOARD_SIZE, std::vector<Piece::Type>(BOARD_SIZE, Piece::PIECE_NONE));
        Piece::initImages();
        board.draw();
    }

    virtual ~Game() {}


    // 将屏幕坐标转换为棋盘行列
    bool screenToBoard(int screenX, int screenY, int& row, int& col) const {
        col = static_cast<int>((screenX - BOARD_MARGIN + GRID_SIZE / 2) / GRID_SIZE);
        row = static_cast<int>((screenY - BOARD_MARGIN + GRID_SIZE / 2) / GRID_SIZE);
        return (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE);
    }

    // 处理鼠标点击（虚函数，子类可以重写）
    virtual void handleMouseClick(int x, int y) = 0;

    // 获取当前玩家
    Piece::Type getCurrentPlayer() const {
        return currentPlayer;
    }

    // 切换玩家
    void switchPlayer() {
        currentPlayer = (currentPlayer == Piece::PIECE_WHITE) ?
            Piece::PIECE_BLACK : Piece::PIECE_WHITE;
    }

    // 判断位置是否为空
    bool isEmpty(int row, int col) const {
        return (row >= 0 && row < BOARD_SIZE &&
            col >= 0 && col < BOARD_SIZE &&
            boardState[row][col] == Piece::PIECE_NONE);
    }

    // 新增快速胜利检查（供外部调用）
    bool checkImmediateWin(Piece::Type player) {
        if (moveHistory.empty()) return false;

        auto lastMove = moveHistory.back();
        return checkWin(lastMove.row, lastMove.col, player);
    }

    // 新增刷新方法
    void refreshBoard() {
        // 1. 重绘背景和棋盘
        board.loadBackground();
        board.draw();

        // 2. 重绘所有棋子
        for (const auto& move : moveHistory) {
            Piece::draw(move.row, move.col, move.player);
        }

        // 3. 弹出消息框提示
        MessageBox(GetHWnd(), L"棋盘刷新成功！", L"系统提示", MB_OK | MB_ICONINFORMATION);
    }

    // 添加悔棋方法
    bool undoMove() {
        // 需要至少2步才能悔棋
        if (moveHistory.size() < 2) {
            return false;
        }

        // 移除最后两步
        for (int i = 0; i < 2; ++i) {
            if (!moveHistory.empty()) {
                MoveRecord lastMove = moveHistory.back();
                boardState[lastMove.row][lastMove.col] = Piece::PIECE_NONE;
                moveHistory.pop_back();
            }
        }

        // 重绘棋盘
        redrawBoard();
        return true;
    }

    // 添加记录移动的方法
    void recordMove(int row, int col, Piece::Type player) {
        if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
            moveHistory.push_back({ row, col, player });
        }
    }

    // 重绘棋盘方法
    void redrawBoard() {
        // 重绘背景和棋盘
		board.loadBackground();
        board.draw();

        // 重绘所有棋子（除了最后两步）
        for (const auto& move : moveHistory) {
            Piece::draw(move.row, move.col, move.player);
        }
    }

    // 检查是否五子连珠
    bool checkWin(int row, int col, Piece::Type player) {
        // 边界安全检查
        if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
            return false;
        }

        // 检查四个方向: 水平、垂直、对角线、反对角线
        int directions[4][2] = { {1, 0}, {0, 1}, {1, 1}, {1, -1} };

        for (int i = 0; i < 4; ++i) {
            int count = 1;  // 当前位置已经有一个棋子

            // 正向检查
            for (int step = 1; step < 5; ++step) {
                int r = row + directions[i][0] * step;
                int c = col + directions[i][1] * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    boardState[r][c] != player) {
                    break;
                }
                count++;
            }

            // 反向检查
            for (int step = 1; step < 5; ++step) {
                int r = row - directions[i][0] * step;
                int c = col - directions[i][1] * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    boardState[r][c] != player) {
                    break;
                }
                count++;
            }

            if (count >= 5) {
                return true;
            }
        }

        return false;
    }

    // 显示胜利信息并询问是否继续
    virtual bool showWinAndAskContinue(Piece::Type winner)  {
        // 弹出消息框
        const wchar_t* winnerText = (winner == Piece::PIECE_WHITE) ? L"白方" : L"黑方";
        int result = MessageBox(GetHWnd(),
            (std::wstring(winnerText) + L"胜利！\n\n是否开始新游戏？").c_str(),
            L"游戏结束",
            MB_ICONQUESTION | MB_YESNO);
		// 设置游戏结束标志，在这里设置防止游戏局面被清空
        gameOver = true;
		// 如果选择否，则退出游戏
		if (result == IDNO) {
			continuePlaying = false;
			return false;
		}
        return true;
    }

    // 添加重置游戏方法
    virtual void resetGame() {
        // 清空棋盘状态
        for (auto& row : boardState) {
            std::fill(row.begin(), row.end(), Piece::PIECE_NONE);
        }

        // 重置游戏状态
        currentPlayer = Piece::PIECE_WHITE;
        gameOver = false;

        // 重绘棋盘
		board.loadBackground();
        board.draw();
    }

    // 添加游戏是否结束的查询方法
    bool isGameOver() const { return gameOver; }

    // 检查禁手（仅对黑棋有效）
    bool checkLimit(int row, int col) {
        if (currentPlayer != Piece::PIECE_BLACK) {
            return false; // 白棋没有禁手
        }

        bool isForbidden = false;
        std::wstring forbiddenType;

        // 检查长连禁手（超过五子连珠）
        if (checkOverline(row, col)) {
            isForbidden = true;
            forbiddenType = L"长连禁手";
        }
        // 检查四四禁手
        else if (checkDoubleFour(row, col)) {
            isForbidden = true;
            forbiddenType = L"四四禁手";
        }
        // 检查三三禁手
        else if (checkDoubleThree(row, col)) {
            isForbidden = true;
            forbiddenType = L"三三禁手";
        }

        if (isForbidden) {
            MessageBox(GetHWnd(),
                (L"黑棋触发" + forbiddenType + L"！\n请重新落子").c_str(),
                L"禁手警告",
                MB_ICONWARNING | MB_OK);
            return true;
        }
        return false;
    }

    // 检查长连禁手（六子或以上）
    bool checkOverline(int row, int col) {
        int directions[4][2] = { {1,0}, {0,1}, {1,1}, {1,-1} };

        for (int i = 0; i < 4; ++i) {
            int count = 1; // 当前落子点

            // 正向计数
            for (int step = 1; step < 6; ++step) {
                int r = row + directions[i][0] * step;
                int c = col + directions[i][1] * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    boardState[r][c] != Piece::PIECE_BLACK) {
                    break;
                }
                count++;
            }

            // 反向计数
            for (int step = 1; step < 6; ++step) {
                int r = row - directions[i][0] * step;
                int c = col - directions[i][1] * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    boardState[r][c] != Piece::PIECE_BLACK) {
                    break;
                }
                count++;
            }

            if (count >= 6) {
                return true;
            }
        }
        return false;
    }

    // 检查双活三
    bool checkDoubleThree(int row, int col) {
        int threeCount = 0;
        int directions[4][2] = { {1,0}, {0,1}, {1,1}, {1,-1} };

        // 临时放置棋子
        boardState[row][col] = Piece::PIECE_BLACK;

        for (int i = 0; i < 4; ++i) {
            if (isOpenThree(row, col, directions[i][0], directions[i][1])) {
                threeCount++;
                if (threeCount >= 2) {
                    boardState[row][col] = Piece::PIECE_NONE; // 恢复
                    return true;
                }
            }
        }

        boardState[row][col] = Piece::PIECE_NONE; // 恢复
        return false;
    }

    // 检查双四
    bool checkDoubleFour(int row, int col) {
        int fourCount = 0;
        int directions[4][2] = { {1,0}, {0,1}, {1,1}, {1,-1} };

        // 临时放置棋子
        boardState[row][col] = Piece::PIECE_BLACK;

        for (int i = 0; i < 4; ++i) {
            if (countOpenFours(row, col, directions[i][0], directions[i][1]) > 0) {
                fourCount++;
                if (fourCount >= 2) {
                    boardState[row][col] = Piece::PIECE_NONE; // 恢复
                    return true;
                }
            }
        }

        boardState[row][col] = Piece::PIECE_NONE; // 恢复
        return false;
    }
    
    // 判断是否是活三（两端都有空位）
    bool isOpenThree(int row, int col, int dx, int dy) {
        // 临时模拟落子
        boardState[row][col] = Piece::PIECE_BLACK;

        // 检查这个方向上的三连子
        int count = 1;
        bool blocked[2] = { false, false };

        // 正向检查
        for (int step = 1; step <= 4; step++) {
            int r = row + dx * step;
            int c = col + dy * step;
            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blocked[0] = true;
                break;
            }
            if (boardState[r][c] != Piece::PIECE_BLACK) {
                if (boardState[r][c] == Piece::PIECE_WHITE) blocked[0] = true;
                break;
            }
            count++;
        }

        // 反向检查
        for (int step = 1; step <= 4; step++) {
            int r = row - dx * step;
            int c = col - dy * step;
            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blocked[1] = true;
                break;
            }
            if (boardState[r][c] != Piece::PIECE_BLACK) {
                if (boardState[r][c] == Piece::PIECE_WHITE) blocked[1] = true;
                break;
            }
            count++;
        }

        // 恢复棋盘状态
        boardState[row][col] = Piece::PIECE_NONE;

        // 是活三的条件：正好3连子且两端都不被阻挡
        return (count == 3) && !blocked[0] && !blocked[1];
    }

    // 计算开放的四的数量（活四或冲四）
    int countOpenFours(int row, int col, int dx, int dy) {
        // 临时模拟落子
        boardState[row][col] = Piece::PIECE_BLACK;
        int fourCount = 0;

        // 检查这个方向上的所有可能的四
        for (int i = 0; i < 5; i++) {
            bool isOpen = true;
            int start = -i;
            int end = 4 - i;

            // 检查这个四连子范围
            for (int step = start; step <= end; step++) {
                int r = row + dx * step;
                int c = col + dy * step;

                // 超出边界或被白棋阻挡
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    (step != 0 && boardState[r][c] == Piece::PIECE_WHITE)) {
                    isOpen = false;
                    break;
                }

                // 检查中间是否有空位
                if (step != 0 && boardState[r][c] != Piece::PIECE_BLACK) {
                    isOpen = false;
                }
            }

            // 检查两端是否开放（活四的条件）
            if (isOpen) {
                int left_r = row + dx * (start - 1);
                int left_c = col + dy * (start - 1);
                int right_r = row + dx * (end + 1);
                int right_c = col + dy * (end + 1);

                bool leftOpen = (left_r >= 0 && left_r < BOARD_SIZE &&
                    left_c >= 0 && left_c < BOARD_SIZE &&
                    boardState[left_r][left_c] == Piece::PIECE_NONE);

                bool rightOpen = (right_r >= 0 && right_r < BOARD_SIZE &&
                    right_c >= 0 && right_c < BOARD_SIZE &&
                    boardState[right_r][right_c] == Piece::PIECE_NONE);

                if (leftOpen && rightOpen) {
                    fourCount++; // 活四
                }
                else if (leftOpen || rightOpen) {
                    fourCount++; // 冲四
                }
            }
        }

        // 恢复棋盘状态
        boardState[row][col] = Piece::PIECE_NONE;
        return fourCount;
    }

    // 落子（虚函数，子类可以重写）修改placePiece方法，加入禁手检查
    virtual void placePiece(int row, int col) {
        if (gameOver) return;  // 游戏已结束不再处理

        if (isEmpty(row, col)) {
            // 黑棋禁手检查
            if (currentPlayer == Piece::PIECE_BLACK && checkLimit(row, col)) {
                return;
            }

            // 执行落子
            boardState[row][col] = currentPlayer;
            Piece::draw(row, col, currentPlayer);
            recordMove(row, col, currentPlayer);

            // 检查胜利
            if (checkWin(row, col, currentPlayer)) {
                showWinAndAskContinue(currentPlayer);
                return;
            }

            // 检查平局
            if (isBoardFull()) {
                showDrawAndAskContinue();
                return;
            }

            // 切换玩家
            switchPlayer();
        }
    }
    // 新增方法：检查棋盘是否已满
    bool isBoardFull() const {
        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (boardState[i][j] == Piece::PIECE_NONE) {
                    return false;
                }
            }
        }
        return true;
    }

    // 新增方法：显示平局对话框
    bool showDrawAndAskContinue() {
        int result = MessageBox(GetHWnd(),
            L"棋盘已满，平局！\n\n是否开始新游戏？",
            L"游戏结束",
            MB_ICONQUESTION | MB_YESNO);
        gameOver = true;
        if (result == IDNO) {
            continuePlaying = false;
            return false;
        }

        return true;
    }
};

// 双人对战模式
class TwoPlayerGame : public Game {
public:
    void handleMouseClick(int x, int y) override {
        if (gameOver) return;

        int row, col;
        if (screenToBoard(x, y, row, col)) {
            placePiece(row, col);
        }
    }
};

// 人机对战模式（AI作为黑方或白方）
class AIGame : public Game {
protected:
    bool aiIsBlack; // AI是否为黑方
    bool isProcessing = false;  // 新增状态锁

    // 检查单个方向的棋型
    PatternType checkLinePattern(int row, int col, int dr, int dc, Piece::Type player) {
        int pieceCount = 0;   // 连续棋子数
        int emptyCount = 0;   // 空位/边界数
        bool blockedLeft = false;
        bool blockedRight = false;

        // 检查正方向
        for (int i = 1; i <= 4; i++) {
            int r = row + dr * i;
            int c = col + dc * i;

            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blockedRight = true;
                break;
            }

            if (boardState[r][c] == player) {
                pieceCount++;
            }
            else if (boardState[r][c] == Piece::PIECE_NONE) {
                emptyCount++;
                break;
            }
            else {
                blockedRight = true;
                break;
            }
        }

        // 检查反方向
        for (int i = 1; i <= 4; i++) {
            int r = row - dr * i;
            int c = col - dc * i;

            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blockedLeft = true;
                break;
            }

            if (boardState[r][c] == player) {
                pieceCount++;
            }
            else if (boardState[r][c] == Piece::PIECE_NONE) {
                emptyCount++;
                break;
            }
            else {
                blockedLeft = true;
                break;
            }
        }

        // 判断棋型
        switch (pieceCount) {
        case 4: return FIVE;    // 连五
        case 3:
            if (emptyCount == 2) return ALIVE_FOUR;  // 活四
            if (emptyCount == 1) return RUSH_FOUR;   // 冲四
            break;
        case 2:
            if (emptyCount == 2) return ALIVE_THREE; // 活三
            if (emptyCount == 1) return SLEEP_THREE; // 眠三
            break;
        case 1:
            if (emptyCount == 2) return ALIVE_TWO;   // 活二
            if (emptyCount == 1) return SLEEP_TWO;   // 眠二
            break;
        }

        return NONE;
    }

    // 计算单个位置的得分
    int calculateScore(int row, int col, Piece::Type player) {
        if (!isEmpty(row, col)) return 0;  // 已有棋子的位置得分为0

        int score = centerWeight[row][col]; // 基础中心权重
        int directions[4][2] = { {1, 0}, {0, 1}, {1, 1}, {1, -1} };

        // 检查四个方向
        for (int i = 0; i < 4; i++) {
            PatternType pattern = checkLinePattern(row, col,
                directions[i][0], directions[i][1], player);
            score += patternScore[pattern];
        }

        return score;
    }
    Position findBestMove() {
        // 先检查AI是否能直接获胜（增量检测）
        if (!moveHistory.empty()) {
            auto lastMove = moveHistory.back();
            int centerRow = lastMove.row;
            int centerCol = lastMove.col;

            // 3x3区域胜利检测
            for (int dr = -1; dr <= 1; ++dr) {
                for (int dc = -1; dc <= 1; ++dc) {
                    int row = centerRow + dr;
                    int col = centerCol + dc;

                    if (row >= 0 && row < BOARD_SIZE &&
                        col >= 0 && col < BOARD_SIZE &&
                        isEmpty(row, col)) {

                        boardState[row][col] = currentPlayer;
                        if (checkWin(row, col, currentPlayer)) {
                            boardState[row][col] = Piece::PIECE_NONE;
                            return { row, col };
                        }
                        boardState[row][col] = Piece::PIECE_NONE;
                    }
                }
            }
        }
        else {
            // 开局时全盘检测（仅执行一次）
            for (int i = 0; i < BOARD_SIZE; ++i) {
                for (int j = 0; j < BOARD_SIZE; ++j) {
                    if (isEmpty(i, j)) {
                        boardState[i][j] = currentPlayer;
                        if (checkWin(i, j, currentPlayer)) {
                            boardState[i][j] = Piece::PIECE_NONE;
                            return { i, j };
                        }
                        boardState[i][j] = Piece::PIECE_NONE;
                    }
                }
            }
        }

        // 检查是否需要拦截玩家（增量检测）
        Piece::Type opponent = (currentPlayer == Piece::PIECE_BLACK) ?
            Piece::PIECE_WHITE : Piece::PIECE_BLACK;

        if (!moveHistory.empty()) {
            auto lastMove = moveHistory.back();
            int centerRow = lastMove.row;
            int centerCol = lastMove.col;

            // 3x3区域拦截检测
            for (int dr = -1; dr <= 1; ++dr) {
                for (int dc = -1; dc <= 1; ++dc) {
                    int row = centerRow + dr;
                    int col = centerCol + dc;

                    if (row >= 0 && row < BOARD_SIZE &&
                        col >= 0 && col < BOARD_SIZE &&
                        isEmpty(row, col)) {

                        boardState[row][col] = opponent;
                        if (checkWin(row, col, opponent)) {
                            boardState[row][col] = Piece::PIECE_NONE;
                            return { row, col };
                        }
                        boardState[row][col] = Piece::PIECE_NONE;
                    }
                }
            }
        }

        // 计算所有空位的评分（保持全盘计算）
        int aiMaxScore = -1;
        int humanMaxScore = -1;
        Position aiBestPos, humanBestPos;

        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (isEmpty(i, j)) {
                    int aiScore = calculateScore(i, j, currentPlayer);
                    int humanScore = calculateScore(i, j, opponent);

                    if (aiScore > aiMaxScore) {
                        aiMaxScore = aiScore;
                        aiBestPos = { i, j };
                    }

                    if (humanScore > humanMaxScore) {
                        humanMaxScore = humanScore;
                        humanBestPos = { i, j };
                    }
                }
            }
        }

        return (aiMaxScore >= humanMaxScore) ? aiBestPos : humanBestPos;
    }
public:
    AIGame() : Game() {
        // 询问玩家先手还是后手
        int result = MessageBox(GetHWnd(),
            L"请选择:\n\n是 - 玩家先手(玩家执黑)\n否 - AI先手(玩家执白)",
            L"选择先手",
            MB_ICONQUESTION | MB_YESNO);

        aiIsBlack = (result == IDNO); // 如果选择否，AI执黑先手

        // 如果AI先手，立即下第一步
        if (aiIsBlack) {
            aiMove();
        }
    }

    void handleMouseClick(int x, int y) override {
        if (gameOver || isProcessing) return;  // 新增状态检查

        // 玩家回合判断逻辑：
        // 如果玩家执黑(!aiIsBlack)且当前是黑棋回合，或者玩家执白(aiIsBlack)且当前是白棋回合
        if ((!aiIsBlack && currentPlayer == Piece::PIECE_BLACK) ||
            (aiIsBlack && currentPlayer == Piece::PIECE_WHITE)) {
            // 玩家回合
            int row, col;
            if (screenToBoard(x, y, row, col)) {
                placePiece(row, col);

                // 玩家下完后，如果不是游戏结束，AI下
                if (!gameOver) {
                    // 小延迟，让玩家看到自己的落子
                    Sleep(250);
                    aiMove();
                }
            }
        }
    }

protected:
    // 修改placePiece方法，区分玩家和AI的禁手处理
    void placePiece(int row, int col) override {
        if (isEmpty(row, col)) {
            // 玩家回合的禁手处理（与双人对战相同）
            if ((!aiIsBlack && currentPlayer == Piece::PIECE_BLACK) ||
                (aiIsBlack && currentPlayer == Piece::PIECE_WHITE)) {

                if (currentPlayer == Piece::PIECE_BLACK && checkLimit(row, col)) {
                    return; // 玩家触发禁手，不允许落子
                }

                boardState[row][col] = currentPlayer;
                Piece::draw(row, col, currentPlayer);
                recordMove(row, col, currentPlayer);

                if (checkWin(row, col, currentPlayer)) {
                    showWinAndAskContinue(currentPlayer);
                    return;
                }

                switchPlayer();
            }
            // AI回合的禁手处理
            else {
                // 如果是黑棋且触发禁手，需要重新选择位置
                if (currentPlayer == Piece::PIECE_BLACK && checkLimit(row, col)) {
                    Position newPos = findValidMove(); // 寻找非禁手的最佳位置
                    placePiece(newPos.row, newPos.col); // 递归调用
                    return;
                }

                boardState[row][col] = currentPlayer;
                Piece::draw(row, col, currentPlayer);
                recordMove(row, col, currentPlayer);

                if (checkWin(row, col, currentPlayer)) {
                    showWinAndAskContinue(currentPlayer);
                    return;
                }

                switchPlayer();
            }
        }
    }

    // 新增方法：寻找有效的非禁手位置
    Position findValidMove() {
        Position bestPos = findBestMove(); // 先获取理论最佳位置

        // 如果是白棋或非禁手位置，直接返回
        if (currentPlayer != Piece::PIECE_BLACK || !checkLimit(bestPos.row, bestPos.col)) {
            return bestPos;
        }

        // 如果是禁手，寻找次优解
        std::vector<Position> candidates;
        int maxScore = -1;

        // 收集所有非禁手位置的评分
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (isEmpty(i, j) && !checkLimit(i, j)) {
                    int score = calculateScore(i, j, currentPlayer);
                    if (score > maxScore) {
                        maxScore = score;
                        candidates.clear();
                        candidates.push_back({ i, j });
                    }
                    else if (score == maxScore) {
                        candidates.push_back({ i, j });
                    }
                }
            }
        }

        // 如果有多个同分位置，随机选择一个
        if (!candidates.empty()) {
            int index = rand() % candidates.size();
            return candidates[index];
        }

        // 如果没有合法位置（极端情况），随机选择一个非禁手位置
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (isEmpty(i, j) && !checkLimit(i, j)) {
                    return { i, j };
                }
            }
        }

        // 实在找不到（理论上不可能），返回原始位置
        return bestPos;
    }

    void aiMove() {
        isProcessing = true;  // 加锁
        Position bestPos = findValidMove();
        placePiece(bestPos.row, bestPos.col);
        isProcessing = false; // 解锁
    }
};

class AIGameEnhanced : public Game {
private:
    bool aiIsBlack; // AI是否为黑方
    bool isProcessing = false;
    int searchDepth = 2; // 搜索深度，默认为2层（AI一步，玩家一步）

    bool showWinAndAskContinue(Piece::Type winner) override {
        // 确定胜利者描述
        std::wstring winnerDesc;
        if (winner == Piece::PIECE_WHITE) {
            winnerDesc = aiIsBlack ? L"玩家(白方)" : L"AI(白方)";
        }
        else {
            winnerDesc = aiIsBlack ? L"AI(黑方)" : L"玩家(黑方)";
        }

        // 保持原有消息框逻辑
        int result = MessageBox(GetHWnd(),
            (winnerDesc + L"胜利！\n\n是否开始新游戏？").c_str(),
            L"游戏结束",
            MB_ICONQUESTION | MB_YESNO);

        gameOver = true;
        if (result == IDNO) {
            continuePlaying = false;
            return false;
        }
        return true;
    }
    // 检查当前玩家能否在下一步直接获胜
    Position checkImmediateWin(Piece::Type player) {
        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (isEmpty(i, j)) {
                    boardState[i][j] = player;
                    if (checkWin(i, j, player)) {
                        boardState[i][j] = Piece::PIECE_NONE;
                        return { i, j };
                    }
                    boardState[i][j] = Piece::PIECE_NONE;
                }
            }
        }
        return { -1, -1 };
    }

    // 检查对手是否有活四、冲四等必须拦截的棋型
    Position checkCriticalThreats(Piece::Type opponent) {
        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (isEmpty(i, j)) {
                    // 模拟对手落子
                    boardState[i][j] = opponent;

                    // 检查是否形成五连
                    if (checkWin(i, j, opponent)) {
                        boardState[i][j] = Piece::PIECE_NONE;
                        return { i, j };
                    }

                    // 检查是否形成活四（两端开放的四连）
                    if (countOpenFours(i, j, opponent) > 0) {
                        boardState[i][j] = Piece::PIECE_NONE;
                        return { i, j };
                    }

                    boardState[i][j] = Piece::PIECE_NONE;
                }
            }
        }
        return { -1, -1 };
    }

    // 计算指定位置落子后形成的开放四数量
    int countOpenFours(int row, int col, Piece::Type player) {
        boardState[row][col] = player;
        int count = 0;
        int directions[4][2] = { {1,0}, {0,1}, {1,1}, {1,-1} };

        for (int i = 0; i < 4; ++i) {
            int dr = directions[i][0], dc = directions[i][1];
            int consecutive = 1;
            bool blocked[2] = { false, false };

            // 正向检查
            for (int step = 1; step <= 4; ++step) {
                int r = row + dr * step;
                int c = col + dc * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    boardState[r][c] != player) {
                    blocked[0] = true;
                    break;
                }
                consecutive++;
            }

            // 反向检查
            for (int step = 1; step <= 4; ++step) {
                int r = row - dr * step;
                int c = col - dc * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE ||
                    boardState[r][c] != player) {
                    blocked[1] = true;
                    break;
                }
                consecutive++;
            }

            if (consecutive >= 4 && (!blocked[0] || !blocked[1])) {
                count++;
            }
        }

        boardState[row][col] = Piece::PIECE_NONE;
        return count;
    }

    // 改进的活三威胁检测
    Position checkLivingThreeThreats(Piece::Type opponent) {
        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (boardState[i][j] == opponent) {
                    auto blocks = getLivingThreeBlockPositions(i, j, opponent);
                    if (!blocks.empty()) {
                        // 选择中心权重更高的拦截点
                        return centerWeight[blocks[0].row][blocks[0].col] >
                            centerWeight[blocks[1].row][blocks[1].col]
                            ? blocks[0] : blocks[1];
                    }
                }
            }
        }
        return { -1, -1 };
    }

    // 精准获取活三的拦截点
    std::vector<Position> getLivingThreeBlockPositions(int row, int col, Piece::Type player) {
        std::vector<Position> blocks;
        int directions[4][2] = { {1,0}, {0,1}, {1,1}, {1,-1} };

        for (int i = 0; i < 4; ++i) {
            int dr = directions[i][0], dc = directions[i][1];
            int consecutive = 1;
            Position ends[2] = { {-1,-1}, {-1,-1} };

            // 正向检查
            for (int step = 1; step <= 4; ++step) {
                int r = row + dr * step;
                int c = col + dc * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) break;

                if (boardState[r][c] == player) {
                    consecutive++;
                }
                else if (boardState[r][c] == Piece::PIECE_NONE) {
                    ends[0] = { r, c };
                    break;
                }
                else break;
            }

            // 反向检查
            for (int step = 1; step <= 4; ++step) {
                int r = row - dr * step;
                int c = col - dc * step;
                if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) break;

                if (boardState[r][c] == player) {
                    consecutive++;
                }
                else if (boardState[r][c] == Piece::PIECE_NONE) {
                    ends[1] = { r, c };
                    break;
                }
                else break;
            }

            // 确认为活三且两端开放
            if (consecutive == 3 && ends[0].row != -1 && ends[1].row != -1) {
                blocks.push_back(ends[0]);
                blocks.push_back(ends[1]);
            }
        }
        return blocks;
    }

    // 威胁检测总入口
    Position checkAllThreats(Piece::Type opponent) {
        // 1. 检查直接获胜威胁（五连）
        Position winPos = checkImmediateWin(opponent);
        if (winPos.row != -1) return winPos;

        // 2. 检查活四/冲四威胁
        Position fourPos = checkCriticalThreats(opponent);
        if (fourPos.row != -1) return fourPos;

        // 3. 新增：检查活三威胁
        Position threePos = checkLivingThreeThreats(opponent);
        if (threePos.row != -1) return threePos;

        return { -1, -1 };
    }


    // 评估函数 - 计算当前棋盘对指定玩家的优势
    int evaluateBoard(Piece::Type player) {
        int totalScore = 0;
        Piece::Type opponent = (player == Piece::PIECE_BLACK) ?
            Piece::PIECE_WHITE : Piece::PIECE_BLACK;

        // 遍历整个棋盘
        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (boardState[i][j] == player) {
                    // 计算玩家在该位置的优势
                    totalScore += calculatePointScore(i, j, player, opponent);
                }
                else if (boardState[i][j] == opponent) {
                    // 减去对手在该位置的优势
                    totalScore -= calculatePointScore(i, j, opponent, player);
                }
            }
        }
        return totalScore;
    }

    // 计算单个位置的得分
    int calculatePointScore(int row, int col, Piece::Type player, Piece::Type opponent) {
        int score = 0;
        int directions[4][2] = { {1, 0}, {0, 1}, {1, 1}, {1, -1} };

        for (int i = 0; i < 4; ++i) {
            // 检查四个方向的棋型
            score += evaluateDirection(row, col, directions[i][0], directions[i][1], player, opponent);
        }

        return score;
    }

    // 评估单个方向的棋型
    int evaluateDirection(int row, int col, int dx, int dy,
        Piece::Type player, Piece::Type opponent) {
        int score = 0;
        int playerCount = 1; // 当前玩家连续棋子数
        int emptyCount = 0;  // 空位数量
        bool blocked[2] = { false, false }; // 两端是否被阻挡

        // 正向检查
        for (int step = 1; step <= 4; ++step) {
            int r = row + dx * step;
            int c = col + dy * step;

            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blocked[0] = true;
                break;
            }

            if (boardState[r][c] == player) {
                playerCount++;
            }
            else if (boardState[r][c] == Piece::PIECE_NONE) {
                emptyCount++;
                break;
            }
            else { // 对手棋子阻挡
                blocked[0] = true;
                break;
            }
        }

        // 反向检查
        for (int step = 1; step <= 4; ++step) {
            int r = row - dx * step;
            int c = col - dy * step;

            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blocked[1] = true;
                break;
            }

            if (boardState[r][c] == player) {
                playerCount++;
            }
            else if (boardState[r][c] == Piece::PIECE_NONE) {
                emptyCount++;
                break;
            }
            else { // 对手棋子阻挡
                blocked[1] = true;
                break;
            }
        }

        // 根据棋型评分
        if (playerCount >= 5) {
            score += 100000; // 五连
        }
        else if (!blocked[0] || !blocked[1]) {
            if (playerCount == 4) {
                if (emptyCount >= 1) score += 10000; // 活四
            }
            else if (playerCount == 3) {
                if (emptyCount >= 2) score += 1000;  // 活三
                else if (emptyCount >= 1) score += 500; // 眠三
            }
            else if (playerCount == 2) {
                if (emptyCount >= 2) score += 100;   // 活二
                else if (emptyCount >= 1) score += 50; // 眠二
            }
        }

        return score;
    }

    // 极大节点（AI回合）
    int maxValue(int depth, int alpha, int beta) {
        if (depth == 0) {
            return evaluateBoard(aiIsBlack ? Piece::PIECE_BLACK : Piece::PIECE_WHITE);
        }

        int maxScore = INT_MIN;
        std::vector<Position> moves = generatePossibleMoves();

        for (const auto& move : moves) {
            // 模拟落子
            boardState[move.row][move.col] = currentPlayer;

            // 切换玩家
            switchPlayer();
            int score = minValue(depth - 1, alpha, beta);

            // 撤销落子
            boardState[move.row][move.col] = Piece::PIECE_NONE;
            switchPlayer();

            maxScore = (std::max)(maxScore, score);
            alpha = (std::max)(alpha, score);

            if (beta <= alpha) {
                break; // Alpha-Beta剪枝
            }
        }

        return maxScore;
    }

    // 极小节点（玩家回合）
    int minValue(int depth, int alpha, int beta) {
        if (depth == 0) {
            return evaluateBoard(aiIsBlack ? Piece::PIECE_BLACK : Piece::PIECE_WHITE);
        }

        int minScore = INT_MAX;
        std::vector<Position> moves = generatePossibleMoves();

        for (const auto& move : moves) {
            // 模拟落子
            boardState[move.row][move.col] = currentPlayer;

            // 切换玩家
            switchPlayer();
            int score = maxValue(depth - 1, alpha, beta);

            // 撤销落子
            boardState[move.row][move.col] = Piece::PIECE_NONE;
            switchPlayer();

            minScore = (std::min)(minScore, score);
            beta = (std::min)(beta, score);

            if (beta <= alpha) {
                break; // Alpha-Beta剪枝
            }
        }

        return minScore;
    }

    // 生成可能的走法（优化性能，只考虑有棋子的周围位置）
    std::vector<Position> generatePossibleMoves() {
        std::vector<Position> moves;
        std::set<std::pair<int, int>> addedPositions;

        // 遍历棋盘，只考虑有棋子周围的空位
        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (boardState[i][j] != Piece::PIECE_NONE) {
                    // 检查周围3x3区域
                    for (int di = -1; di <= 1; ++di) {
                        for (int dj = -1; dj <= 1; ++dj) {
                            int r = i + di;
                            int c = j + dj;

                            if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE &&
                                boardState[r][c] == Piece::PIECE_NONE &&
                                addedPositions.find({ r, c }) == addedPositions.end()) {

                                moves.push_back({ r, c });
                                addedPositions.insert({ r, c });
                            }
                        }
                    }
                }
            }
        }

        // 如果没有找到任何可能的走法（开局情况）
        if (moves.empty() && isEmpty(BOARD_SIZE / 2, BOARD_SIZE / 2)) {
            moves.push_back({ BOARD_SIZE / 2, BOARD_SIZE / 2 });
        }

        return moves;
    }

    // 获取最佳走法（使用MinMax算法）
    Position getBestMove() {
        Piece::Type aiPlayer = currentPlayer;
        Piece::Type humanPlayer = (aiPlayer == Piece::PIECE_BLACK) ? Piece::PIECE_WHITE : Piece::PIECE_BLACK;

        // 第一优先级：AI能否直接获胜？
        Position winPos = checkImmediateWin(aiPlayer);
        if (winPos.row != -1) return winPos;

        // 第二优先级：拦截玩家威胁（包括活三）
        Position blockPos = checkAllThreats(humanPlayer);
        if (blockPos.row != -1) return blockPos;


        // 第三优先级：使用Minimax算法决策
        int bestScore = INT_MIN;
        Position bestMove;
        std::vector<Position> moves = generatePossibleMoves();
        int alpha = INT_MIN;
        int beta = INT_MAX;

        for (const auto& move : moves) {
            // 模拟落子
            boardState[move.row][move.col] = currentPlayer;

            // 切换玩家
            switchPlayer();
            int score = minValue(searchDepth - 1, alpha, beta);

            // 撤销落子
            boardState[move.row][move.col] = Piece::PIECE_NONE;
            switchPlayer();

            // 更新最佳走法
            if (score > bestScore ||
                (score == bestScore && centerWeight[move.row][move.col] > centerWeight[bestMove.row][bestMove.col])) {
                bestScore = score;
                bestMove = move;

                // 更新alpha值
                alpha = (std::max)(alpha, bestScore);
            }
        }

        return bestMove;
    }

public:
    AIGameEnhanced() : Game() {
        // 询问玩家先手还是后手
        int result = MessageBox(GetHWnd(),
            L"请选择:\n\n是 - 玩家先手(玩家执黑)\n否 - AI先手(玩家执白)",
            L"选择先手",
            MB_ICONQUESTION | MB_YESNO);

        aiIsBlack = (result == IDNO); // 如果选择否，AI执黑先手

        // 如果AI先手，立即下第一步
        if (aiIsBlack) {
            aiMove();
        }
    }

    void handleMouseClick(int x, int y) {
        if (gameOver || isProcessing) return;  // 新增状态检查

        if ((!aiIsBlack && currentPlayer == Piece::PIECE_BLACK) ||
            (aiIsBlack && currentPlayer == Piece::PIECE_WHITE)) {
            // 玩家回合
            int row, col;
            if (screenToBoard(x, y, row, col)) {
                placePiece(row, col);

                // 玩家下完后，如果不是游戏结束，AI下
                if (!gameOver) {
                    // 小延迟，让玩家看到自己的落子
                    Sleep(10);
                    aiMove();
                }
            }
        }
    }

protected:
    void aiMove() {
        isProcessing = true;

        // 检查游戏状态
        if (isBoardFull()) {
            showDrawAndAskContinue();
            isProcessing = false;
            return;
        }

        Position bestPos = getBestMove();
        placePiece(bestPos.row, bestPos.col);

        isProcessing = false;
    }

    void placePiece(int row, int col) override {
        if (isEmpty(row, col)) {
            // 玩家回合的禁手处理
            if ((!aiIsBlack && currentPlayer == Piece::PIECE_BLACK) ||
                (aiIsBlack && currentPlayer == Piece::PIECE_WHITE)) {

                if (currentPlayer == Piece::PIECE_BLACK && checkLimit(row, col)) {
                    return; // 玩家触发禁手，不允许落子
                }

                boardState[row][col] = currentPlayer;
                Piece::draw(row, col, currentPlayer);
                recordMove(row, col, currentPlayer);

                if (checkWin(row, col, currentPlayer)) {
                    showWinAndAskContinue(currentPlayer);
                    return;
                }

                switchPlayer();
            }
            // AI回合的禁手处理
            else {
                // 如果是黑棋且触发禁手，需要重新选择位置
                if (currentPlayer == Piece::PIECE_BLACK && checkLimit(row, col)) {
                    // 这里简化处理，实际应该重新搜索
                    Position newPos = getBestMove();
                    placePiece(newPos.row, newPos.col);
                    return;
                }

                boardState[row][col] = currentPlayer;
                Piece::draw(row, col, currentPlayer);
                recordMove(row, col, currentPlayer);

                if (checkWin(row, col, currentPlayer)) {
                    showWinAndAskContinue(currentPlayer);
                    return;
                }

                switchPlayer();
            }
        }
    }
};

// AI对战AI模式（演示用）
class AIVsAIGame : public Game {
public:
    bool isProcessing = false;

    // 检查单个方向的棋型
    PatternType checkLinePattern(int row, int col, int dr, int dc, Piece::Type player) {
        int pieceCount = 0;   // 连续棋子数
        int emptyCount = 0;   // 空位/边界数
        bool blockedLeft = false;
        bool blockedRight = false;

        // 检查正方向
        for (int i = 1; i <= 4; i++) {
            int r = row + dr * i;
            int c = col + dc * i;

            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blockedRight = true;
                break;
            }

            if (boardState[r][c] == player) {
                pieceCount++;
            }
            else if (boardState[r][c] == Piece::PIECE_NONE) {
                emptyCount++;
                break;
            }
            else {
                blockedRight = true;
                break;
            }
        }

        // 检查反方向
        for (int i = 1; i <= 4; i++) {
            int r = row - dr * i;
            int c = col - dc * i;

            if (r < 0 || r >= BOARD_SIZE || c < 0 || c >= BOARD_SIZE) {
                blockedLeft = true;
                break;
            }

            if (boardState[r][c] == player) {
                pieceCount++;
            }
            else if (boardState[r][c] == Piece::PIECE_NONE) {
                emptyCount++;
                break;
            }
            else {
                blockedLeft = true;
                break;
            }
        }

        // 判断棋型
        switch (pieceCount) {
        case 4: return FIVE;    // 连五
        case 3:
            if (emptyCount == 2) return ALIVE_FOUR;  // 活四
            if (emptyCount == 1) return RUSH_FOUR;   // 冲四
            break;
        case 2:
            if (emptyCount == 2) return ALIVE_THREE; // 活三
            if (emptyCount == 1) return SLEEP_THREE; // 眠三
            break;
        case 1:
            if (emptyCount == 2) return ALIVE_TWO;   // 活二
            if (emptyCount == 1) return SLEEP_TWO;   // 眠二
            break;
        }

        return NONE;
    }

    // 计算单个位置的得分
    int calculateScore(int row, int col, Piece::Type player) {
        if (!isEmpty(row, col)) return 0;  // 已有棋子的位置得分为0

        int score = centerWeight[row][col]; // 基础中心权重
        int directions[4][2] = { {1, 0}, {0, 1}, {1, 1}, {1, -1} };

        // 检查四个方向
        for (int i = 0; i < 4; i++) {
            PatternType pattern = checkLinePattern(row, col,
                directions[i][0], directions[i][1], player);
            score += patternScore[pattern];
        }

        return score;
    }
    Position findBestMove() {
        // 先检查AI是否能直接获胜（增量检测）
        if (!moveHistory.empty()) {
            auto lastMove = moveHistory.back();
            int centerRow = lastMove.row;
            int centerCol = lastMove.col;

            // 3x3区域胜利检测
            for (int dr = -1; dr <= 1; ++dr) {
                for (int dc = -1; dc <= 1; ++dc) {
                    int row = centerRow + dr;
                    int col = centerCol + dc;

                    if (row >= 0 && row < BOARD_SIZE &&
                        col >= 0 && col < BOARD_SIZE &&
                        isEmpty(row, col)) {

                        boardState[row][col] = currentPlayer;
                        if (checkWin(row, col, currentPlayer)) {
                            boardState[row][col] = Piece::PIECE_NONE;
                            return { row, col };
                        }
                        boardState[row][col] = Piece::PIECE_NONE;
                    }
                }
            }
        }
        else {
            // 开局时全盘检测（仅执行一次）
            for (int i = 0; i < BOARD_SIZE; ++i) {
                for (int j = 0; j < BOARD_SIZE; ++j) {
                    if (isEmpty(i, j)) {
                        boardState[i][j] = currentPlayer;
                        if (checkWin(i, j, currentPlayer)) {
                            boardState[i][j] = Piece::PIECE_NONE;
                            return { i, j };
                        }
                        boardState[i][j] = Piece::PIECE_NONE;
                    }
                }
            }
        }

        // 检查是否需要拦截玩家（增量检测）
        Piece::Type opponent = (currentPlayer == Piece::PIECE_BLACK) ?
            Piece::PIECE_WHITE : Piece::PIECE_BLACK;

        if (!moveHistory.empty()) {
            auto lastMove = moveHistory.back();
            int centerRow = lastMove.row;
            int centerCol = lastMove.col;

            // 3x3区域拦截检测
            for (int dr = -1; dr <= 1; ++dr) {
                for (int dc = -1; dc <= 1; ++dc) {
                    int row = centerRow + dr;
                    int col = centerCol + dc;

                    if (row >= 0 && row < BOARD_SIZE &&
                        col >= 0 && col < BOARD_SIZE &&
                        isEmpty(row, col)) {

                        boardState[row][col] = opponent;
                        if (checkWin(row, col, opponent)) {
                            boardState[row][col] = Piece::PIECE_NONE;
                            return { row, col };
                        }
                        boardState[row][col] = Piece::PIECE_NONE;
                    }
                }
            }
        }

        // 计算所有空位的评分（保持全盘计算）
        int aiMaxScore = -1;
        int humanMaxScore = -1;
        Position aiBestPos, humanBestPos;

        for (int i = 0; i < BOARD_SIZE; ++i) {
            for (int j = 0; j < BOARD_SIZE; ++j) {
                if (isEmpty(i, j)) {
                    int aiScore = calculateScore(i, j, currentPlayer);
                    int humanScore = calculateScore(i, j, opponent);

                    if (aiScore > aiMaxScore) {
                        aiMaxScore = aiScore;
                        aiBestPos = { i, j };
                    }

                    if (humanScore > humanMaxScore) {
                        humanMaxScore = humanScore;
                        humanBestPos = { i, j };
                    }
                }
            }
        }

        return (aiMaxScore >= humanMaxScore) ? aiBestPos : humanBestPos;
    }

    Position findValidMove() {
        Position bestPos = findBestMove(); // 先获取理论最佳位置

        // 如果是白棋或非禁手位置，直接返回
        if (currentPlayer != Piece::PIECE_BLACK || !checkLimit(bestPos.row, bestPos.col)) {
            return bestPos;
        }

        // 如果是禁手，寻找次优解
        std::vector<Position> candidates;
        int maxScore = -1;

        // 收集所有非禁手位置的评分
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (isEmpty(i, j) && !checkLimit(i, j)) {
                    int score = calculateScore(i, j, currentPlayer);
                    if (score > maxScore) {
                        maxScore = score;
                        candidates.clear();
                        candidates.push_back({ i, j });
                    }
                    else if (score == maxScore) {
                        candidates.push_back({ i, j });
                    }
                }
            }
        }

        // 如果有多个同分位置，随机选择一个
        if (!candidates.empty()) {
            int index = rand() % candidates.size();
            return candidates[index];
        }

        // 如果没有合法位置（极端情况），随机选择一个非禁手位置
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (isEmpty(i, j) && !checkLimit(i, j)) {
                    return { i, j };
                }
            }
        }

        // 实在找不到（理论上不可能），返回原始位置
        return bestPos;
    }

    // AI落子方法
    void aiMove() {
        if (isProcessing || gameOver) return;

        isProcessing = true;

        // 检查游戏状态
        if (isBoardFull()) {
            showDrawAndAskContinue();
            isProcessing = false;
            return;
        }

        Position bestPos = findValidMove();

        // 执行落子（使用基类方法）
        placePiece(bestPos.row, bestPos.col);

        isProcessing = false;

        // 如果不是游戏结束，继续下一步
        if (!gameOver) {
            Sleep(10); // 适当延迟
            aiMove();   // 递归调用
        }

    }



public:
    AIVsAIGame() : Game(Piece::PIECE_BLACK) {  // 直接调用Game构造函数，指定黑棋先手
        // 直接开始游戏，不等待定时器
        aiMove(); // 立即执行第一步
    }

    ~AIVsAIGame() {}

    // 完全禁用鼠标交互
    void handleMouseClick(int x, int y) override {}

protected:
    // 重写落子方法确保正确处理禁手
    void placePiece(int row, int col) override {
        if (isEmpty(row, col)) {
            // 黑棋需要检查禁手
            if (currentPlayer == Piece::PIECE_BLACK) {
                if (checkLimit(row, col)) {
                    Position newPos = findValidMove();
                    placePiece(newPos.row, newPos.col);
                    return;
                }
            }

            boardState[row][col] = currentPlayer;
            Piece::draw(row, col, currentPlayer);
            recordMove(row, col, currentPlayer);

            if (checkWin(row, col, currentPlayer)) {
                showWinAndAskContinue(currentPlayer);
                return;
            }

            switchPlayer();
        }
    }
};
